package com.alibaba.citrus.cr.unified.inventory.facade.service;

import java.math.BigDecimal;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

import com.alibaba.citrus.cr.unified.inventory.repository.InvoiceOrderReadRepository;
import com.alibaba.citrus.cr.unified.inventory.utils.InfoUtil;
import com.alibaba.citrus.cr.common.exception.FacadeException;
import com.alibaba.citrus.cr.common.util.JsonUtil;
import com.alibaba.citrus.cr.unified.inventory.validator.InvoiceOrderValidator;
import com.alibaba.lattice2.epoch.sdk.model.Result;

import com.epoch.app.crplatformenhance.enums.OrganizationTypeEnum;
import com.epoch.app.crplatformenhance.model.dto.GetLoginEmployOrganizationPermissionsRequest;
import com.epoch.app.crplatformenhance.sdo.OrganizationSDO;
import com.epoch.app.crplatformenhance.service.CrPlatformEnhanceService;
import com.epoch.app.crunifiedinventory.api.allocateorderread.service.AllocateOrderReadService;
import com.epoch.app.crunifiedinventory.api.invoiceorderread.service.InvoiceOrderReadService;
import com.epoch.app.crunifiedinventory.domain.allocateorder.service.AllocateOrderService;
import com.epoch.app.crunifiedinventory.domain.invoiceorder.model.InvoiceOrder;
import com.epoch.app.crunifiedinventory.domain.invoiceorder.service.InvoiceOrderService;
import com.epoch.app.crunifiedinventory.domain.invoiceorderdetail.model.InvoiceOrderDetail;
import com.epoch.app.crunifiedinventory.domain.invoiceorderdetail.service.InvoiceOrderDetailService;
import com.epoch.app.crunifiedinventory.dto.request.AllocateOrderDetailSearchRequest;
import com.epoch.app.crunifiedinventory.dto.request.InvoiceOrderQueryRequest;
import com.epoch.app.crunifiedinventory.dto.response.AllocateOrderDetailVO;
import com.epoch.app.crunifiedinventory.model.dto.InvoiceDetailRequest;
import com.epoch.app.crunifiedinventory.model.dto.InvoiceOrderDetailDTO;
import com.epoch.app.crunifiedinventory.model.dto.InvoiceOrderSearchRequest;
import com.epoch.app.crunifiedinventory.model.dto.InvoiceOrderSearchResponse;
import com.epoch.app.crunifiedinventory.model.dto.InvoiceSourceOrderInfoDTO;
import com.epoch.app.crunifiedinventory.sdo.InvoiceOrderDetailSDO;
import com.epoch.app.crunifiedinventory.sdo.InvoiceOrderSDO;
import com.google.common.collect.Lists;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

@Component
@Primary
public class InvoiceOrderReadServiceImpl implements InvoiceOrderReadService {
    @Autowired
    private InvoiceOrderReadRepository queryInvoiceOrderList;

    @Resource
    InvoiceOrderService invoiceOrderService;
    @Resource
    InvoiceOrderDetailService invoiceOrderDetailService;
    @Resource
    AllocateOrderService allocateOrderService;
    @Resource
    AllocateOrderReadService allocateOrderReadService;
    @Autowired
    private InvoiceOrderReadRepository invoiceOrderReadRepository;
    @Resource
    private CrPlatformEnhanceService otsPlatformEnhanceService;
    private static final Integer MAX_PAGE_SIZE = 1000;


    @Override
    public Result<List<InvoiceOrderSDO>> queryInvoiceOrderList(InvoiceOrderQueryRequest request) {
        //校验
        InvoiceOrderValidator.check(request);

        //查询数据
        Result<List<InvoiceOrderSDO>> list = queryInvoiceOrderList.queryInvoiceOrderList(request);

        list.setSuccess(true);

        return list;
    }

    @Override
    public Result<InvoiceOrderSearchResponse> search(InvoiceOrderSearchRequest invoiceOrderSearchRequest) {
        InvoiceOrderSearchResponse response = new InvoiceOrderSearchResponse();
        if (StringUtils.isBlank(invoiceOrderSearchRequest.getInvoiceOrderId())){
            return Result.success(response);
        }
        InvoiceOrderQueryRequest invoiceOrderQueryRequest = new InvoiceOrderQueryRequest();
        invoiceOrderQueryRequest.setInvoiceOrderId(invoiceOrderSearchRequest.getInvoiceOrderId());
        Result<List<InvoiceOrder>> result = invoiceOrderService.loadList(invoiceOrderQueryRequest);
        if (result == null || CollectionUtils.isEmpty(result.getResult())){
            return Result.success(response);
        }
        InvoiceOrder invoiceOrderSDO = result.getResult().get(0);
        if (invoiceOrderSDO == null ){
            return Result.success(response);
        }
        //
        InvoiceOrderSDO invoiceMainOrder = invoiceOrderReadRepository.queryInvoiceOrderById(invoiceOrderSDO.getInvoiceOrderId());
        List<InvoiceOrderDetailSDO> item = invoiceMainOrder.getDetailList();
        if (CollectionUtils.isEmpty(item)) {
            throw new FacadeException("OTS-03-003-15-004");
        }
        String outAllocateOrderId=item.get(0).getSourceOrderId();
        AllocateOrderDetailSearchRequest searchRequest = new AllocateOrderDetailSearchRequest();
        searchRequest.setOutAllocateOrderId(outAllocateOrderId);
        searchRequest.setLimit(MAX_PAGE_SIZE);
//        Result<List<AllocateOrderDetailVO>> search = allocateOrderReadService.search(searchRequest);
        Result<List<AllocateOrderDetailVO>> search = allocateOrderReadService.searchData(searchRequest);
        if (search != null && CollectionUtils.isNotEmpty(search.getResult())){
            AllocateOrderDetailVO detailVO = search.getResult().get(0);
            InvoiceSourceOrderInfoDTO dto = new InvoiceSourceOrderInfoDTO();
            dto.setCreateTime(detailVO.getCreateTime());
            dto.setCreator(detailVO.getCreator());
            dto.setDocDate(detailVO.getDocDate());
            dto.setDocDateStr(detailVO.getDocDateStr());
            dto.setShipAreaName(detailVO.getShipAreaName());
            dto.setReceiveAreaName(detailVO.getReceiveAreaName());
            dto.setShipWarehouseName(detailVO.getShipWarehouseName());
            dto.setReceiveWarehouseName(detailVO.getReceiveWarehouseName());
            dto.setSourceOrderCode(detailVO.getCode());
            response.setDetail(dto);
        }
//        AllocateOrderLoadListRequest allocateOrderLoadListRequest = new AllocateOrderLoadListRequest();
//        allocateOrderLoadListRequest.setOutAllocateOrderId(invoiceOrderSDO.getSourceOrderId());
//        Result<List<AllocateOrder>> allocateOrderList = allocateOrderService.loadAllocateOrderList(allocateOrderLoadListRequest);
//        if (allocateOrderList != null && CollectionUtils.isNotEmpty(allocateOrderList.getResult())){
//
//        }

        InvoiceDetailRequest invoiceDetailRequest = new InvoiceDetailRequest();
        invoiceDetailRequest.setInvoiceOrderId(invoiceOrderSearchRequest.getInvoiceOrderId());
        Result<List<InvoiceOrderDetail>> listResult = invoiceOrderDetailService.loadList(invoiceDetailRequest);
        //查询登录账户分子公司
        GetLoginEmployOrganizationPermissionsRequest permissionsRequest = new GetLoginEmployOrganizationPermissionsRequest(OrganizationTypeEnum.COMPANY.getCode());
        Result<List<OrganizationSDO>> loginEmployOrganizationPermissions = otsPlatformEnhanceService.getLoginEmployOrganizationPermissions(permissionsRequest);
        if (loginEmployOrganizationPermissions != null && CollectionUtils.isNotEmpty(loginEmployOrganizationPermissions.getResult())){
            List<String> collect = loginEmployOrganizationPermissions.getResult().stream().map(OrganizationSDO::getCode).collect(Collectors.toList());
            if (!collect.contains(invoiceOrderSDO.getCompanyCode())){
                return Result.success(response);
            }
        }
        List<InvoiceOrderDetailDTO> list = Lists.newArrayList();
        if (listResult != null && CollectionUtils.isNotEmpty(listResult.getResult())){
            for (InvoiceOrderDetail invoiceOrderDetail : listResult.getResult()) {
                InvoiceOrderDetailDTO dto = JsonUtil.convert(invoiceOrderDetail,InvoiceOrderDetailDTO.class);
                if (dto == null){
                    continue;
                }
                if (search != null && CollectionUtils.isNotEmpty(search.getResult())){
                    for (AllocateOrderDetailVO detailVO : search.getResult()) {
//                        String s = InfoUtil.deleteZeroPrefix(invoiceOrderDetail.getScItemId());
//                        String scItemCode = detailVO.getScItemCode();
                        if (Objects.equals(InfoUtil.deleteZeroPrefix(invoiceOrderDetail.getScItemId()),
                                detailVO.getScItemCode())){
                            dto.setSourceQuantity(detailVO.getQuantity());
                        }
                    }
                }
                //2022.0217 因为发票的价格放大了100倍, 这里查出来要缩小100倍  开票金额也缩小
                if (StringUtils.isNotBlank(dto.getPrice())){
                    dto.setPrice(new BigDecimal(dto.getPrice().trim()).movePointLeft(2).toString());
                }
                if (StringUtils.isNotBlank(dto.getSubTotalAmount())){
                    dto.setSubTotalAmount(new BigDecimal(dto.getSubTotalAmount().trim()).movePointLeft(2).toString());
                }
                list.add(dto);
            }
//            response.setList(listResult.getResult());
            response.setList(list);
        }
        return Result.success(response);
    }
}
